/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.transaction.core.service.impl;

import com.lvyh.lightframe.transaction.annotation.MyTransactionListener;
import com.lvyh.lightframe.transaction.common.config.TransactionApplicationConfig;
import com.lvyh.lightframe.transaction.common.domain.Participant;
import com.lvyh.lightframe.transaction.core.context.ApplicationContextHolder;
import com.lvyh.lightframe.transaction.core.message.TransactionMessage;
import com.lvyh.lightframe.transaction.core.service.TransactionMessageService;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class TransactionMessageServiceImpl implements TransactionMessageService {

    private TransactionMessage transactionMessage;

    @Override
    public void start(TransactionApplicationConfig transactionApplicationConfig) {
        transactionMessage = ApplicationContextHolder.getBean(TransactionMessage.class.getName());
        transactionMessage.init(transactionApplicationConfig);
        setTransactionListener();
    }

    private void setTransactionListener() {
        List<MyTransactionListener> listeners = new ArrayList<>();
        Map<String, Object> beans = ApplicationContextHolder.getApplicationContext().getBeansWithAnnotation(Component.class);

        beans.forEach((k, v) -> {
            Class clazz = v.getClass();
            Method[] methods = clazz.getMethods();
            listeners.addAll(Stream.of(methods).map(this::getAnnotation).filter(a -> Objects.nonNull(a)).collect(Collectors.toList()));
        });
        transactionMessage.listen(listeners);
    }


    @Override
    public void sendMessage(Participant participant) {
        transactionMessage.send(participant);
    }

    private MyTransactionListener getAnnotation(Method method) {
        return method.getAnnotation(MyTransactionListener.class);
    }

}
